package com.tianqu.tms.www.car.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.MemberUpdateCarPortBo;
import com.tianqu.tms.dao.TmsConfigureDaoimp;
import com.tianqu.tms.dao.TmsDao;
import com.tianqu.tms.dto.MemberRentalLocationInfo;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;

/**
 * @author mufeiyu
 * 高级管理 - 结果保存 controller
 */
public class CarSeniorManagementResultController extends TmsController {
	private Logger logger = Logger.getLogger(CarSeniorManagementResultController.class);
	// button的Flag
	public static String BTNFLAG = "btnFlag";
	
	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();		
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftViewHelper viewhelper = new CarPendingLiftViewHelper();
			CarPendingLiftViewHelper view = (CarPendingLiftViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			CarPendingLiftActionForm form = (CarPendingLiftActionForm) uc.getInputForm();
			String memberId = view.getMemId();
			Member member = Member.getInstance();
			member=member.findMemberInfoByMemId(memberId);
			if("true".equals(uc.getAttribute(BTNFLAG))){//履历按钮
				String addSerial = form.getSerial();
				if(!StringUtil.isNullOrBlank(addSerial)){
					String businessNo = "";
					if(!StringUtil.isNullOrBlank(addSerial)){
						if(!StringUtil.isNullOrBlank(member.getBusinessNo())){
							businessNo = member.getBusinessNo()+ "," +addSerial;
						}else {
							businessNo = addSerial;
						}
					}
					
					String floors = "";
					int rentalArea = form.getRentalArea();
					if(rentalArea > 0){
						if(!StringUtil.isNullOrBlank(member.getFloors())){
							floors = member.getFloors() + "," + rentalArea;
						} else {
							floors = String.valueOf(rentalArea);
						}
					}
										
					TmsUserProfile profile = uc.getUserProfile();
					member.setUpdateUserId(profile.getUniqueId());
					member.setBusinessNo(businessNo);
					member.setMemId(Integer.valueOf(memberId));
					member.setFloors(floors);
					//合同编号List更新
					member.updateMemberBusinessNoInfo(member);
				}
			}else {//修改保存
				String businessNo = member.getBusinessNo();
				MemberRentalLocationInfo memberRentalLocationInfo = Member.getInstance().findMemberLocationInfoCount(businessNo);
				String usedAnnualTransactionVolume = memberRentalLocationInfo.getUsedAnnualTransactionVolume();
				String usedCarPort = memberRentalLocationInfo.getUsedCarPort();
				TmsUserProfile profile = uc.getUserProfile();
				member.setUpdateUserId(profile.getUniqueId());
				member.setAnnualTransactionVolume(Integer.valueOf(StringUtils.isNotBlank(usedAnnualTransactionVolume)?usedAnnualTransactionVolume:"0"));
				member.setCarPort(Integer.valueOf(Integer.valueOf(StringUtils.isNotBlank(usedCarPort)?usedCarPort:"0")));
				member.setFragileStickerFreePort(Integer.valueOf(StringUtil.removeDH(form.getFragileStickerFreePort())));
				member.setRecommend(form.getRecommend());
				member.setMemId(Integer.valueOf(memberId));
				member.setIdentityRange(convertIdentityRangeToString(form.getIdentityRange()));
				member.setTmpIdentityRange(convertIdentityRangeToString(form.getTmpIdentityRange()));
				member.setContractType(form.getContractType());
				member.setContractTime(form.getContractTime());
				//member表对应更新
				member.updateMemberInfo(member);
			}
			
			viewhelper = setDetailInfo(member,viewhelper);
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			controller.commit();
			
			if("false".equals(uc.getAttribute(BTNFLAG))){
				MobileMessage message = new MobileMessage();
				message.putValue("MemberId", memberId);
				message.setMessage("TMS高级管理无法同步[高级管理]接口,商户ID为#MemberId#");
				
				// 获得市场编号
				TmsConfigureDaoimp tmsConfigureDao = (TmsConfigureDaoimp) TmsConfigureDaoimp.getInstance(TmsDao.TMS_CONFIGURE);
				String userMarket = tmsConfigureDao.getConfig("maketNo");
				MemberUpdateCarPortBo api = new MemberUpdateCarPortBo();
				if(StringUtil.isNotBlank(member.getRecommend())) api.setRecommend(Integer.parseInt(member.getRecommend()));
				if(StringUtil.isNotBlank(userMarket))  api.setUmid(Integer.parseInt(userMarket));
				api.setMobileMessage(message);
				api.setMemberId(memberId);
				api.setCarPort(member.getCarPort());
				
				PullingExecutor.getInstance().submit(api);				
			}
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	
	private String convertIdentityRangeToString(String[] IdentityRange){
		if(IdentityRange == null) return "";
		String r = "";
		int size = IdentityRange.length;
		for (int i = 0; i < size; i++) {
			r += IdentityRange[i];
			if(size - i >1) r +=",";
		}
		return r;
	}
	
	/**
	 * view赋值
	 * @return
	 */
	private CarPendingLiftViewHelper setDetailInfo(Member member,CarPendingLiftViewHelper viewhelper) throws TmsDaoException{
		Codes code = Codes.getInstance();
		
		//商户编号
		viewhelper.setMemId(String.valueOf(member.getMemId()));
		//商户名称
		viewhelper.setMemName(member.getShortName());
		//商户状态
		if(member.getMemStatus()== 1){
			viewhelper.setMemStatus("正常");
		}else if(member.getMemStatus()== 2){
			viewhelper.setMemStatus("删除");
		}else if(member.getMemStatus()== 3){
			viewhelper.setMemStatus("禁用");
		}else{
			viewhelper.setMemStatus("");
		}
		viewhelper.setContractType(member.getContractType());
		//注册时间
		viewhelper.setInsertTime(member.getInsertTime());
		MemberRentalLocationInfo memberRentalLocationInfo = member.findMemberRentalLocationInfoCount(member.getBusinessNo());
		String unusedAnnualTransactionVolume = memberRentalLocationInfo.getUnusedAnnualTransactionVolume();
		String unusedCarPort = memberRentalLocationInfo.getUnusedCarPort();
		viewhelper.setUnusedAnnualTransactionVolume(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedAnnualTransactionVolume)?Integer.parseInt(unusedAnnualTransactionVolume):0));
		viewhelper.setUnusedCarPort(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedCarPort)?Integer.parseInt(unusedCarPort):0));
		
		//允许库存停放数量
		viewhelper.setCarPortStr(StringUtil.getPointBetweenThree(member.getCarPort()));
		//允许库存登记数量
		viewhelper.setAnnualTransactionVolume(StringUtil.getPointBetweenThree(member.getAnnualTransactionVolume()));
		//易碎贴免费数量
		viewhelper.setFragileStickerFreePort(StringUtil.getPointBetweenThree(member.getFragileStickerFreePort()));	
		//车源推荐权重
		List recommendListlist = code.getCodeslistByItemId(Codes.RECOMMEND_TYPE);
		viewhelper.setCarRecommendList(recommendListlist);
		viewhelper.setRecommend(code.getItemValueByItemIdAndItemCode(Codes.RECOMMEND_TYPE, Integer.valueOf(member.getRecommend())));
		//合同编号
		viewhelper.setSerial("");
		//租位编号
		viewhelper.setLocationSerial("");
		//租位类型
		viewhelper.setRentalType("");
		//租位面积
		viewhelper.setAcreage("");
		//车位数量
		viewhelper.setRentalCarPort("");
		//租位位置
		viewhelper.setAddress("");
		//开始时间
		viewhelper.setStartDate("");
		//结束时间
		viewhelper.setEndDate("");
		//租位按钮显示Flag
		viewhelper.setLocationAddBtnFlag("");
		//有效识别道闸
		viewhelper.setIdentityRangeList(convertIdentityRangeStr(member.getIdentityRange()));
				
				//临时识别道闸
		viewhelper.setTmpIdentityRangeList(convertIdentityRangeStr(member.getTmpIdentityRange()));
				
		
		//合同编号
		String businessNo = member.getBusinessNo();
		viewhelper.setBusinessNo(businessNo);
		List<RentalContractInfo> rentalList = new ArrayList<RentalContractInfo>(); 
		if(!StringUtil.isNullOrBlank(businessNo)){
			String[] list= businessNo.split(",");
			List<String> serialList = Arrays.asList(list);
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();			
			for(int i=0;i<serialList.size();i++){
				contractInfo = contractInfo.findContractInfoBySerial(serialList.get(i));
				contractInfo.setNum(i+1);
				if(i%2 == 0){
					contractInfo.setCssFlag(1);
				}else {
					contractInfo.setCssFlag(2);
				}
				rentalList.add(contractInfo);
			}
		}
		//关联租位信息
		viewhelper.setRentalLocationInfoList(rentalList);
//		viewhelper.setIdentityRangeStr(convertIdentityRangeStr(member.getIdentityRange()));
//		viewhelper.setTmpIdentityRangeStr(convertIdentityRangeStr(member.getTmpIdentityRange()));
		
		return viewhelper;
	}
//	private String convertIdentityRangeStr(String identityRangeCode) throws TmsDaoException{
//		if (StringUtil.isNullOrBlank(identityRangeCode)) return "";
//		Codes code = Codes.getInstance();
//		String r = "";
//		String[] tmp = identityRangeCode.split(",");
//		for (int i = 0; i < tmp.length; i++){
//			int itemCode = StringUtils.isNumeric(tmp[i])?Integer.parseInt(tmp[i]):-1;
//			if(i!=0) r += ",";
//			r += code.getItemValueByItemIdAndItemCode(Codes.GATEWAY_TYPE, itemCode);
//		}
//		return r;
//	}
	private List convertIdentityRangeStr(String identityRangeCode) throws TmsDaoException{
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		if(StringUtil.isNotBlank(identityRangeCode)){
			String[] tmp = identityRangeCode.split(",");
			for (int i = 0; i < tmp.length; i++){
				int itemCode = StringUtils.isNumeric(tmp[i])?Integer.parseInt(tmp[i]):-1;
				map.put(itemCode, itemCode);
			}
		}
		List codeslist = Codes.getInstance().getCodeslistByItemId(Codes.GATEWAY_TYPE);
		for (Object object : codeslist) {
			String checked = "";
			HashMap codesMap = (HashMap)object;
			if(map.get(codesMap.get("itemCode"))!=null ) checked = "checked";
			codesMap.put("checked", checked);
		}
		return codeslist;
	}
	
}
